package cn.player.utils;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import cntv.player.core.util.LogUtil;

public class DESUtil {

	public static final String PSD = "87654321";

	/**
	 * DES加密
	 * 
	 * @param clearText
	 *            待加密明文
	 * @param password
	 *            加密的密码，长度必须大于8位
	 * @return
	 */
	public static byte[] encrypt(byte[] clearText, String password) {
		try {

			SecureRandom random = new SecureRandom();
			 DESKeySpec desKey = new DESKeySpec(password.getBytes());
			 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			 SecretKey securekey = keyFactory.generateSecret(desKey);
			 
			 IvParameterSpec ivParameterSpec = new IvParameterSpec(password.getBytes());
			 
//				KeyGenerator kgen = KeyGenerator.getInstance("DES");
//				SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
//				random.setSeed(password.getBytes());
//				kgen.init(random);
//				SecretKey securekey = kgen.generateKey();

			// Cipher对象实际完成加密操作
			// Cipher cipher = Cipher.getInstance("DES");
			// Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.ENCRYPT_MODE, securekey, ivParameterSpec, random);
			// 现在，获取数据并加密
			// 正式执行加密操作
			return cipher.doFinal(clearText);
		} catch (Exception e) {
			LogUtil.i("zl", "DES encrypt Exception e = " + e);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * DES 解密
	 * 
	 * @param cipherText
	 *            待解密的密文
	 * @param password
	 *            解密的密码，长度必须大于8位
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] cipherText, String password) {
		try {
			SecureRandom random = new SecureRandom();
			 DESKeySpec desKey = new DESKeySpec(password.getBytes());
			 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			 SecretKey securekey = keyFactory.generateSecret(desKey);
			 IvParameterSpec ivParameterSpec = new IvParameterSpec(password.getBytes());
			 
//				KeyGenerator kgen = KeyGenerator.getInstance("DES");
//				SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
//				random.setSeed(password.getBytes());
//				kgen.init(random);
//				SecretKey securekey = kgen.generateKey();

			// Cipher对象实际完成解密操作
			// Cipher cipher = Cipher.getInstance("DES");
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.DECRYPT_MODE, securekey, ivParameterSpec, random);
			// 真正开始解密操作
			return cipher.doFinal(cipherText);
		} catch (Exception e) {
			// TODO: handle exception
			LogUtil.i("zl", "DES decrypt Exception e = " + e);
			e.printStackTrace();
		}
		return null;
	}

}
